package com.zm.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
和事务相关的工具类，他包含了：开启事务，提交事务，回滚事务和释放连接
 */
public class TransactionManager {

    //获得连接工具类
    private ConnectionUtil connectionUtil;


    /**
    * 开启事务
    */
    public void beginTransation(){
        //对于当前线程的连接将自动提交事务关闭，改为手动自动提交
        try {
            connectionUtil.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionUtil.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionUtil.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 释放链接
     */
    public void removeConn(){
        try {
            connectionUtil.getThreadConnection().close();//并不是关闭连接，而是返回连接给连接池
            //将当前线程绑定的连接解绑
            connectionUtil.removeConn();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }
}
